<template>
  <div class="app-main">
    <div class="app-main-left">
      <tag-tree pcode="B03" @checkedKeys="getCheckedKeys" @selectedKeys="getSelectedKeys" />
    </div>
    <div class="app-main-right">
      <a-card :bordered="false" style="margin-bottom: 10px">
        <!-- 查询区域 -->
        <div class="table-page-search-wrapper" style="position: relative">
          <div class="search-wrapper-btn">
            <a-button type="link" @click="show = !show">
              <span v-if="!show">展开<a-icon type="down"/></span>
              <span v-else>收起<a-icon type="up"/></span>
            </a-button>
          </div>
          <a-form-model :label-col="labelCol" :wrapper-col="wrapperCol" @keyup.enter.native="onQuery">
            <div class="mode_item">
              <a-form-model-item label="案事件名称">
                <a-input v-model="form.incidentName" placeholder="请输入" @blur="onQuery" />
              </a-form-model-item>
              <a-form-model-item label="案事件编号">
                <j-search-select-tag
                  placeholder="请选择"
                  v-model="form.incidentCode"
                  :dictOptions="incidentCodeOptions"
                  @change="onQuery"
                />
              </a-form-model-item>
              <a-form-model-item label="任务编号">
                <j-search-select-tag
                  placeholder="请选择"
                  v-model="form.taskCode"
                  :dictOptions="taskCodeOptions"
                  @change="onQuery"
                />
              </a-form-model-item>
            </div>
            <div class="mode_item" v-show="show">
              <a-form-model-item label="手机号码">
                <a-input v-model="form.phone" placeholder="请输入" @blur="onQuery" />
              </a-form-model-item>
              <a-form-model-item label="姓名/代号">
                <a-input v-model="form.name" placeholder="请输入" @blur="onQuery" />
              </a-form-model-item>
              <a-form-model-item label="号码归属地">
                <j-search-select-tag
                  placeholder="请选择"
                  v-model="form.phoneArea"
                  :dictOptions="phoneAreaOptions"
                  @change="onQuery"
                />
              </a-form-model-item>
            </div>
            <div class="mode_item mode_item_none" v-show="show">
              <a-form-model-item label="入库时间" class="zdy-form-item-label">
                <a-radio-group buttonStyle="solid" v-model="form.timeType" @change="onQuery">
                  <a-radio-button v-for="(item, key) in options" :key="key" :value="item.value">
                    {{ item.text }}
                  </a-radio-button>
                </a-radio-group>
                <a-range-picker
                  v-if="form.timeType === '0'"
                  :allowClear="true"
                  v-model="rangePickerTime"
                  valueFormat="YYYY-MM-DD"
                  format="YYYY-MM-DD"
                  @change="rangePickerChange"
                  style="margin-left: 10px"
                />
              </a-form-model-item>
            </div>
            <div style="margin-top: 20px">
              <a-form-model-item :wrapper-col="{ offset: 0 }" style="margin-bottom: 0">
                <a-button class="Indormation-list-CX" type="primary" @click="onQuery"> 查询 </a-button>
                <a-button class="Indormation-list-CX" style="margin-left: 10px" @click="onResetForm"> 重置 </a-button>
              </a-form-model-item>
            </div>
          </a-form-model>
        </div>
      </a-card>
      <a-card :bordered="false">
        <!-- 操作按钮区域 -->
        <div class="table-operator">
          <div>
            <span style="position: relative;margin-right:8px;">
              <a-button type="primary" :disabled="isTagDisabled" @click="handleAdd">新增案事件</a-button>
              <a-tooltip
                placement="topLeft"
                title="请勾选重点人标签，新增重点人"
                style="position: absolute;right: -7px;top: -14px;"
              >
                <a-icon type="question-circle" />
              </a-tooltip>
            </span>
            <a-button @click="handleExport()">导出</a-button>
            <a-button @click="handleDelete" :disabled="isDisabled">移除</a-button>
          </div>
        </div>
        <!-- 表格展示 -->
        <div class="table-page-content">
          <z-table
            ref="table"
            rowKey="id"
            :showAlert="false"
            :showSelection="true"
            :loading="loading"
            :columns="columns"
            :dataSource="pageData"
            @selectedRow="onSelectedRow"
            @change="onTableChange"
          >
            <template slot="phone" slot-scope="text, record">
              <span>{{ text }}</span>
              <a-tag v-if="record.isSamplePerson" style="margin-left:20px;" color="red">负样本人员</a-tag>
            </template>
            <!--操作-->
            <template slot="action" slot-scope="text, record">
              <a-button @click="handleDetails(record)" type="link" style="padding:0;">查看</a-button>
              <a-divider type="vertical" />
              <a-button @click="handleEdit(record)" type="link" style="padding:0;">编辑</a-button>
              <a-divider type="vertical" />
              <a-button @click="handleDelete(record)" type="link" style="padding:0;">移除</a-button>
            </template>
          </z-table>
        </div>
        <!--弹窗区域 -->
        <!--页面来源pageType， 1：案事件管理 2：任务情报列表 3： 配置情报列表 4： 重点人列表 5：任务情报管理 6：种子号码列表 7：协查函列表、8 审批列表   10 负样本人员库 11 时空碰撞 -->
        <add-caseModal
          ref="addCaseModalId"
          title="新增案事件"
          :pageType="4"
          :labelId="selectTagKeysJoin"
          moduleType="caseEvent"
          @createSuccess="modalOk"
        />
        <edit-modal ref="editModalRef" title="编辑重点人" type="keyPersonnel" @ok="modalOk" />
        <delete-modal ref="deleteModalRef" title="提示" type="keyPersonnel" @ok="modalOk" />
      </a-card>
    </div>
  </div>
</template>

<script>
import moment from 'moment'
import * as peopleApi from '@/api/wxSmuggle/people.js'
import { DisabledAuthFilterMixin } from '@/mixins/DisabledAuthFilterMixin'
import { downLoadFileReader } from '@/utils/export-util/util'
import tagTree from '../modules/tagTree'
import AddCaseModal from '../modules/AddCaseModal'
import editModal from './modules/editModal'
import deleteModal from './modules/deleteModal'
import { querySimpleByPhoneList } from '@/utils/util'
export default {
  components: {
    tagTree,
    editModal,
    deleteModal,
    AddCaseModal
  },
  mixins: [DisabledAuthFilterMixin],
  data() {
    return {
      moment,
      labelCol: { span: 7 },
      wrapperCol: { span: 17 },
      rangePickerTime: [],
      show: false,
      closeTip: false,
      loading: false,
      visible: false,
      handleModalBool: false,
      isDisabled: true,
      isTagDisabled: true,
      reloading: false,
      selectKeys: [],
      selectTagKeys: [],
      selectTagKeysJoin: null,
      form: {},
      incidentCodeOptions: [],
      taskCodeOptions: [],
      phoneAreaOptions: [],
      options: [
        { value: '2', text: '今天' },
        { value: '1', text: '昨天' },
        { value: '3', text: '近三天' },
        { value: '4', text: '近七天' },
        { value: '0', text: '自定义' }
      ],
      columns: [
        {
          title: '序号',
          width: 60,
          align: 'center',
          dataIndex: 'order',
          customRender: (text, record, index) =>
            `${(this.pageFilter.pageNo - 1) * this.pageFilter.pageSize + (index + 1)}` //序号分页后连续
        },
        {
          title: '任务编号',
          dataIndex: 'taskCode',
          width: 80,
          align: 'center',
          customRender: text => {
            return <j-ellipsis value={text} length={16} />
          }
        },
        {
          title: '任务名称',
          dataIndex: 'taskName',
          width: 80,
          align: 'center',
          customRender: text => {
            return <j-ellipsis value={text} length={10} />
          }
        },
        {
          title: '案事件编号',
          dataIndex: 'incidentCode',
          width: 80,
          align: 'center',
          customRender: text => {
            return <j-ellipsis value={text} length={16} />
          }
        },
        {
          title: '案事件名称',
          dataIndex: 'incidentName',
          width: 80,
          align: 'center',
          customRender: text => {
            return <j-ellipsis value={text} length={12} />
          }
        },
        {
          title: '手机号码',
          dataIndex: 'phone',
          width: 120,
          align: 'center',
          scopedSlots: { customRender: 'phone' }
        },
        {
          title: '姓名/代号',
          dataIndex: 'name',
          width: 80,
          align: 'center',
          scopedSlots: { customRender: 'name' }
        },
        {
          title: '归属地',
          dataIndex: 'phoneArea',
          width: 80,
          align: 'center',
          customRender: text => {
            return <j-ellipsis value={text} length={10} />
          }
        },
        {
          title: '标签',
          dataIndex: 'labelName',
          width: 80,
          align: 'center',
          customRender: text => {
            return <j-ellipsis value={text} length={10} />
          }
        },
        {
          title: '指数',
          dataIndex: 'indexNum',
          width: 40,
          align: 'center',
          customRender: text => {
            return text?text:0
          }
        },
        {
          title: '入库时间',
          dataIndex: 'createTime',
          width: 100,
          align: 'center'
        },
        {
          title: '操作',
          width: 160,
          align: 'center',
          dataIndex: 'action',
          scopedSlots: { customRender: 'action' }
        }
      ],
      pageFilter: {
        pageNo: 1,
        pageSize: 10
      },
      pageData: {}
    }
  },
  created() {},
  async mounted() {
    this.initList()
    this.onQuery()
  },
  methods: {
    onQuery() {
      this.pageFilter.pageNo = 1
      this.refreshTable()
    },
    onResetForm() {
      this.form = {}
      this.pageFilter.pageNo = 1
      this.pageFilter.pageSize = 10
      this.refreshTable()
    },
    onSelectedRow(keys) {
      this.selectKeys = keys
      this.isDisabled = keys.length > 0 ? false : true
    },
    onTableChange(pagination, pageFilter, sorter) {
      let keyMap = { currentPage: 'pageNo' }
      let paginations = Object.keys(pagination).reduce((newData, key) => {
        let newKey = keyMap[key] || key
        newData[newKey] = pagination[key]
        return newData
      }, {})
      this.pageFilter = Object.assign({}, this.pageFilter, paginations)
      this.refreshTable()
    },
    refreshTable() {
      let form = Object.assign({}, this.form, this.pageFilter)
      this.loading = true
      peopleApi
        .wxFocusPersonList(form)
        .then(res => {
          if (res.success) {
            this.pageData = res.result ? res.result : {}
            this.loading = false
            this.$refs.table.onClearRowKeys()
            //判断是否是负样本号码，并添加负样本标签(电话号码字段：phoneNumber传1，phone传2，msisdn传3)
            querySimpleByPhoneList(this, 2, this.pageData.records)
          } else {
            this.loading = false
          }
        })
        .catch(e => {
          this.loading = false
          this.$message.warn('请求失败！')
        })
    },
    initList() {
      let data = [{ text: '全部', value: '' }]
      // 案事件编号集合
      peopleApi.getIncidentCodeList1().then(res => {
        if (res.success) {
          let arr = [...new Set(res.result)] //数组去重es6
          let datas =
            arr && arr.length > 0
              ? arr.map(key => {
                  return { text: key, value: key }
                })
              : []
          this.incidentCodeOptions = [...data, ...datas]
        }
      })
      // 任务编号集合
      peopleApi.getTaskCodeList().then(res => {
        if (res.success) {
          let arr = [...new Set(res.result)] //数组去重es6
          let datas =
            arr && arr.length > 0
              ? arr.map(key => {
                  return { text: key, value: key }
                })
              : []
          this.taskCodeOptions = [...data, ...datas]
        }
      })
      // 号码归属地集合
      peopleApi.getPhoneAreaList().then(res => {
        if (res.success) {
          let arr = [...new Set(res.result)] //数组去重es6
          let datas =
            arr && arr.length > 0
              ? arr.map(key => {
                  return { text: key, value: key }
                })
              : []
          this.phoneAreaOptions = [...data, ...datas]
        }
      })
    },
    // 弹窗成功接收
    modalOk(type) {
      // 成功时，重载列表
      this.onQuery()
    },
    // 获取重点人标签-点击复选框触发
    getCheckedKeys(keys) {
      console.log(keys)
      this.selectTagKeys = keys
      this.selectTagKeysJoin = keys.join(',')
      this.isTagDisabled = keys.length > 0 ? false : true
    },
    // 获取重点人标签-点击树节点触发
    getSelectedKeys(keys) {
      console.log(keys)
      this.$set(this.form, 'labelId', keys.join(','))
      this.onQuery()
    },
    // 导出
    handleExport(record) {
      console.log(record)
      let that = this
      let selectList = this.$refs.table.getSelectedRows()
      let idList1 = selectList.map(v => v.id).filter(obj => obj !== null && obj !== undefined && obj !== '')
      let idList2 = record && Object.keys(record).length > 0 && record.id ? [record.id] : []
      let params = Object.assign(
        {},
        {
          idList: selectList.length > 0 ? idList1 : idList2,
          focusPersonQuery: this.form
        }
      )
      let total = Object.keys(this.pageData).length > 0 && this.pageData.total ? this.pageData.total : 0
      let title = total > 10000 ? '确定导出所有数据？' : '是否确认导出？'
      this.$confirm({
        title: title,
        okText: '确定',
        onOk() {
          peopleApi.focusPersonExportXls(params).then(async res => {
            const fileName = '重点人数据.xls'
            await downLoadFileReader(res, fileName)
          })
        }
      })
    },
    // 移除
    handleDelete(record) {
      let selectList = this.$refs.table.getSelectedRows()
      let idList1 = selectList
        .map(v => {
          return {
            id: v.id,
            labelName: v.labelName,
            name: v.name,
            phone: v.phone,
            phoneArea: v.phoneArea,
            taskId: v.taskId
          }
        })
        .filter(obj => obj !== null && obj !== undefined && obj !== '')
      let idList2 =
        record && Object.keys(record).length > 0 && record.id
          ? [
              {
                id: record.id,
                labelName: record.labelName,
                name: record.name,
                phone: record.phone,
                phoneArea: record.phoneArea,
                taskId: record.taskId
              }
            ]
          : []
      let idList = selectList.length > 0 ? idList1 : idList2
      this.$refs.deleteModalRef.edit(idList)
    },
    // 详情
    handleDetails(record) {
      this.$router.push({
        path: `/people/details/${record.id}`,
        query: {
          taskId: record.taskId
        }
      })
    },
    // 编辑
    handleEdit(record) {
      this.$refs.editModalRef.edit(record)
    },
    // 新增案事件
    handleAdd() {
      this.$refs.addCaseModalId.show()
    },
    // 入库时间
    rangePickerChange(date) {
      this.$set(this.form, 'startTime', date[0])
      this.$set(this.form, 'endTime', date[1])
      this.onQuery()
    },
    /** 重新加载组件 */
    reload() {
      this.reloading = true
      this.$nextTick(() => (this.reloading = false))
    }
  }
}
</script>
<style lang="less" scoped>
.mode_item {
  display: flex;
  border-bottom: 1px #dadada dashed;
  > div {
    flex: 0 0 30%;
  }
  & > * {
    width: 100%;
    margin-bottom: 0;
    padding: 5px 0;
  }
  &.mode_item_none {
    > div {
      flex: inherit;
    }
  }
  .zdy-form-item-label {
    /deep/.ant-form-item-label {
      width: 90px;
    }
    &.xzqh-form-item-label {
      /deep/.ant-form-item-control-wrapper {
        .ant-form-item-children {
          display: -webkit-box;
        }
      }
      /deep/.area-select {
        // margin-top: 4px;
        line-height: 1;
      }
      /deep/.select-tag {
        width: 162px !important;
        margin-left: 10px;
        margin-top: 3px;
      }
      // /deep/.area-select .area-selected-trigger {
      //   line-height: 1.15;
      // }
      // /deep/.ant-select-lg .ant-select-selection--single{
      //   height: 34px;
      // }
      // /deep/.ant-select-lg .ant-select-selection__rendered {
      //   line-height: 34px;
      //   font-size: 14px;
      // }
    }
  }
}
.search-wrapper-btn {
  position: absolute;
  right: 0;
  top: 15px;
  z-index: 1;
}
/deep/.table-operator {
  display: flex;
  justify-content: space-between;
}
/deep/.table-custom-cols {
  top: -48px !important;
}
.custom-ewm {
  padding: 14px;
  background-color: #fff;
  border: 1px #ccc solid;
  border-radius: 6px;
  display: flex;
  flex-direction: column;
}
/deep/.ant-dropdown-menu-item {
  text-align: center;
  border-bottom: 1px #f5f5f5 solid;
  &:last-child {
    border-bottom: 0;
  }
}
/deep/.anticon.anticon-down {
  font-size: 14px !important;
}

.table-page-content {
  /deep/.ant-table-thead > tr > th,
  /deep/.ant-table-tbody > tr > td {
    padding-left: 0;
    padding-right: 0;
  }
  /deep/.ant-table-thead > tr:first-child > th:first-child,
  /deep/.ant-table-tbody > tr > td:first-child {
    padding-left: 10px;
  }
}

.app-main {
  display: flex;
  flex-direction: row;
  align-items: stretch;
}
.app-main-left {
  flex: 0 0 260px;
  flex-direction: column;
  display: flex;
  margin-right: 12px;
  background-color: #fff;
}
.app-main-right {
  // width: 100%;
  flex: 1;
  flex-direction: column;
  display: flex;
}
</style>
